<template>
  <div id="history">
    <dv-full-screen-container class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <div v-else class="host-body">
        <div class="d-flex jc-center">
          <dv-decoration-10 style="width:33.3%;height:.0625rem;"/>
          <div class="d-flex jc-center">
            <dv-decoration-8 :color="['#568aea', '#000000']" style="width:2.5rem;height:.625rem;"/>
            <div class="title">
              <span class="title-text">SEG易损件计数系统 Digital Tooling Counting System</span>
              <dv-decoration-6
                  class="title-bototm"
                  :reverse="true"
                  :color="['#50e3c2', '#67a1e5']"
                  style="width:3.125rem;height:.1rem;"
              />
            </div>
            <dv-decoration-8
                :reverse="true"
                :color="['#568aea', '#000000']"
                style="width:2.5rem;height:.625rem;"
            />
          </div>
          <dv-decoration-10 style="width:33.3%;height:.0625rem; transform: rotateY(180deg);"/>
        </div>

        <!-- 第二行 -->
        <div class="d-flex jc-between px-2">
          <div class="d-flex" style="width: 40%">
            <div
                class="react-right ml-4"
                style="width: 6.25rem; text-align: left;background-color: #0f1325;"
            >
              <span class="react-before"></span>
            </div>
            <div class="react-right ml-3" style="background-color: #0f1325;">
            </div>
          </div>
          <div style="width: 40%" class="d-flex">
            <div class="react-left  mr-3">
            </div>
            <div
                class="react-left mr-4"
                style="width: 6.25rem; background-color: #0f1325; text-align: right;"
            >
              <span class="react-after"></span>
              <span class="text">{{ nowDate }}</span>
            </div>
          </div>
        </div>
      </div>
      <div id="consume">
        <div class="consume_top">
          <el-form :inline="true" :model="lineSearch" ref="lineSearch" class="demo-form-inline"
                   style="width: 100%;display: flex;justify-content: space-around;">
            <el-form-item><span style="color: #0f1325;font-size: 0.2rem;">{{ displayName }}</span></el-form-item>
            <el-form-item label="产线" style="color: #fff">
              <el-select v-model="lineSearch.lineValue" placeholder="请选择产线">
                <el-option
                    v-for="item in lineSearch.proline_data"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期" style="color: #fff">
              <div class="block">
                <el-date-picker
                    v-model="lineSearch.dateTime"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期" style="width: 6rem">
                </el-date-picker>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="obtainConsumeList(lineSearch.lineValue,lineSearch.dateTime,page.current_page,page.page_size)">
                查询
              </el-button>
              <el-button type="success"
                         @click="exportExcel(lineSearch.lineValue,lineSearch.dateTime)">导出
              </el-button>
              <el-button @click="reset">重置</el-button>
              <el-button @click="goback">返回</el-button>
            </el-form-item>
          </el-form>

        </div>

        <div class="consume_middle">
          <el-table
              :data="consumeRecord"
              style="width: 100%;" header-cell-class-name="text_ce" cell-class-name="text_ce">
            <el-table-column
                type="index"
                :index="obtainIndex"
                label="序号"
                width="180">
            </el-table-column>
            <!--            <el-table-column
                            prop="deviceCode"
                            label="设备编号"
                            width="180">
                        </el-table-column>-->
            <el-table-column
                prop="productionLine"
                label="产线"
                width="180">
            </el-table-column>
            <el-table-column
                prop="stationNum"
                label="工位">
            </el-table-column>
            <el-table-column
                prop="stationName"
                label="工位名称">
            </el-table-column>
            <el-table-column
                prop="deviceName"
                label="易损件名称">
            </el-table-column>
            <el-table-column
                prop="resetTimes"
                label="消耗数量">
            </el-table-column>
          </el-table>
        </div>
        <div class="consume_bottom">
          <el-pagination
              background
              layout="prev, pager, next,total"
              :pager-count="page.pager_count"
              :total="page.totalCount"
              :current-page="page.current_page"
              :page-size="page.page_size" style="width: 5rem"
              @current-change="handleCurrentChange">
          </el-pagination>

        </div>
      </div>
    </dv-full-screen-container>
  </div>
</template>

<script>

export default {
  data() {
    return {
      displayName: '历史消耗查询',
      nowDate: "", // 当前日期
      loading: true,
      lineSearch: {
        proline_data: [],
        lineValue: "",
        dateTime: []
      },
      consumeRecord: [],
      page: {
        totalCount: 0,
        pager_count: 5,
        current_page: 1,
        page_size: 10,
      }
    };
  },
  created() {
    this.fillDate();
    this.$http.get("/opc/device/get_product_line").then(res => {
      if (res.data.code === 0) {
        this.lineSearch.proline_data = res.data.data
      }
    })
  },
  components: {},
  mounted() {
    this.cancelLoading();
    this.currentTime();
    this.obtainConsumeList('', this.lineSearch.dateTime, this.page.current_page, this.page.page_size)
  },
  methods: {
    cancelLoading() {
      setTimeout(() => {
        this.loading = false;
      }, 100);
    },
    format(dateTime) {
      //获取年月日，时间
      let year = dateTime.getFullYear();
      let mon = (dateTime.getMonth() + 1) < 10 ? "0" + (dateTime.getMonth() + 1) : dateTime.getMonth() + 1;
      let data = dateTime.getDate() < 10 ? "0" + (dateTime.getDate()) : dateTime.getDate();
      let hour = dateTime.getHours() < 10 ? "0" + (dateTime.getHours()) : dateTime.getHours();
      let min = dateTime.getMinutes() < 10 ? "0" + (dateTime.getMinutes()) : dateTime.getMinutes();
      let seon = dateTime.getSeconds() < 10 ? "0" + (dateTime.getSeconds()) : dateTime.getSeconds();
      return year + "-" + mon + "-" + data + " " + hour + ":" + min + ":" + seon;
    },
    obtainConsumeList(proLine, dateTime, pageNo, pageSize) {
      if (dateTime === undefined || dateTime == null || dateTime.length < 0) {
        this.$message({
          showClose: true,
          message: '开始时间和结束时间不能为空',
          type: 'error',
          duration: 1500
        });
        return
      }
      let startTime = dateTime[0]
      let endTime = dateTime[1]
      if (startTime != null && startTime !== '') {
        startTime = this.format(startTime)
      }
      if (endTime != null && endTime !== '') {
        endTime = this.format(endTime)
      }
      this.$http.get("/opc/history/history_list", {
        params: {
          proLine: proLine,
          startTime: startTime,
          endTime: endTime,
          pageNo: pageNo,
          pageSize: pageSize
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.consumeRecord = res.data.data.rows
          this.page.totalCount = res.data.data.totalCount
        }
      })
    },
    reload() {//局部刷新
      this.isShow = false;
      this.$nextTick(() => {
        this.isShow = true
      })
    },
    reset() {
      this.reload()
      this.fillDate()
      this.lineSearch.lineValue = ''
      this.obtainConsumeList('', this.lineSearch.dateTime, this.page.current_page, this.page.page_size)
    },
    goback() {
      this.$router.go(-1)
    },
    handleCurrentChange(val) {
      this.page.current_page = val
      this.obtainConsumeList(this.lineSearch.lineValue, this.lineSearch.dateTime, val, this.page.page_size)
    },
    obtainIndex(index) {
      return index + (this.page.current_page - 1) * this.page.page_size + 1
    },
    currentTime() {
      setInterval(this.formatDate, 500);
    },
    abnormalFormat(row) {
      return row.recordType === '1' ? "是" : "否";
    },
    exportExcel(line, dateTime) {
      if (dateTime === undefined || dateTime == null || dateTime.length < 0) {
        this.$message({
          showClose: true,
          message: '开始时间和结束时间不能为空',
          type: 'error',
          duration: 1500
        });
        return
      }
      let startTime = dateTime[0]
      let endTime = dateTime[1]
      if (startTime != null && startTime !== '') {
        startTime = this.format(startTime)
      }
      if (endTime != null && endTime !== '') {
        endTime = this.format(endTime)
      }
      this.$http.get("/opc/excel/history_list", {
            params: {
              proLine: line,
              startTime: startTime,
              endTime: endTime,
            },
            responseType: "blob"
          },
      ).then((res) => {
        const link = document.createElement('a')
        let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'})
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.download = this.displayName //下载的文件名
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }).catch(error => {
        alert(error)
      })
    },
    formatDate() {
      let date = new Date();
      let year = date.getFullYear(); // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      let week = date.getDay(); // 星期
      let weekArr = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
      let hour = date.getHours(); // 时
      hour = hour < 10 ? "0" + hour : hour; // 如果只有一位，则前面补零
      let minute = date.getMinutes(); // 分
      minute = minute < 10 ? "0" + minute : minute; // 如果只有一位，则前面补零
      let second = date.getSeconds(); // 秒
      second = second < 10 ? "0" + second : second; // 如果只有一位，则前面补零
      this.nowDate = `${year}/${month}/${day} ${hour}:${minute}:${second} ${weekArr[week]}`;
    },
    fillDate() {
      let now = new Date()
      let year = now.getFullYear()
      let month = now.getMonth()
      let day = now.getDate()
      // this.lineSearch.dateTime[0] = new Date(year, month, 1)
      // this.lineSearch.dateTime[1] = new Date(year, month, day, 23, 59, 59)
      this.$set(this.lineSearch, "dateTime", [new Date(year, month, 1), new Date(year, month, day, 23, 59, 59)])
      // console.log(this.lineSearch.dateTime[0])
    }
  },
  beforeDestroy() {
    if (this.formatDate) {
      clearInterval(this.formatDate); // 在Vue实例销毁前，清除时间定时器
    }
  }
};
</script>

<style lang="scss">
@import "../../assets/scss/history";


</style>
